//
//  ComposeViewController.swift
//  Sinaweibo
//
//  Created by 谌桃 on 15/12/5.
//  Copyright © 2015年 ryan.chen. All rights reserved.
//


import UIKit
import SnapKit
import SVProgressHUD
//代码生成视图控制器 它的根视图是透明的

class ComposeViewController: UIViewController {
    
    //MARK: 监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func selectPicture() {
        //取消键盘第一响应者
        textView.resignFirstResponder()
        //显示图片选择器的视图
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(226 + 88 + 60)
        }
    }
    
    @objc private func send() {
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        let parmaters = ["access_token": UserAccountViewModel().token , "status": textView.text]
        if selectorVC.imageList.count > 0 {
            //发布图片微博
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //获取图片的二进制数据
            let imageData = UIImagePNGRepresentation(selectorVC.imageList.first!)!
            NetWorkTools.sharedTools.uploadImage(urlString, imageData: imageData, parameters: parmaters, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(errorTip)
                    return
                }
                print(result)
                SVProgressHUD.showSuccessWithStatus("发布成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            })
            
        } else {
            //没有图片 发送文本微博
            NetWorkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parmaters) { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(errorTip)
                    return
                }
                print(result)
                SVProgressHUD.showSuccessWithStatus("发布成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
        
        
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if selectorVC.imageList.count == 0 {
            textView.becomeFirstResponder()
        }
        
    }
    
    
    //懒加载子控件
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.backgroundColor = UIColor.randomColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        return tv
        }()
    
    private lazy var placeHolderText: UILabel = UILabel(title: "分享新鲜事", color: UIColor.lightGrayColor(), fontSize: 18, margin: 0)
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var selectorVC: PictureSelectorViewController = PictureSelectorViewController()
    
    //析构函数 不能够卸载扩展中
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}

extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //设置发送按钮状态 + 占位文本显示/隐藏
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderText.hidden = textView.hasText()
    }
}

//设置UI的extension
extension ComposeViewController {
    //MARK:  设置UI
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        // ScrollView + 导航视图控制器 当先添加顶部约束  就会开启 toplayoutGuide 在这种情况下尽量
        //从上向下进行布局约束
        setNavBar()
        
        setTextView()
        
        setToolBar()
        
        registerNotification()
        
        setSelectorImageView()
        
        
    }
    
    private func setSelectorImageView() {
        //添加子视图控制器
        addChildViewController(selectorVC)
        //添加子视图
        view.addSubview(selectorVC.view)
        
        //将toolBar移到视图最顶层
        view.bringSubviewToFront(toolBar)
        //设置约束
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWiiChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    @objc private func keyboardWiiChange(n: NSNotification) {
        print(n)
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        
        //更改toolbar的底部约束
        let offset = -height + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新
            self.view.layoutIfNeeded()
        }
    }
    
    
    private func setToolBar() {
        // 添加工具栏按钮
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            
            let btn = UIButton()
            btn.setImage(UIImage(named: dict["imageName"]!), forState: .Normal)
            btn.setImage(UIImage(named: dict["imageName"]! + "_highlighted"), forState: .Highlighted)
            if let action = dict["actionName"] {
                //添加点击事件
                //如果不是在方法 中直接给定action对应的字符串 需要制定selector 类型
                btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            btn.sizeToFit()
            let item = UIBarButtonItem(customView: btn)
            items.append(item)
            
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        
        toolBar.items = items
        view.addSubview(toolBar)
        
        
        //设置布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(40)
        }
    }
    
    private func setTextView() {
        view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(height / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeHolderText)
        placeHolderText.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    //MARK: 设置导航栏
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        //自定义导航条 titleView
        let v = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = v
        
        let weiboLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17, margin: 0)
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14, margin: 0)
        
        v.addSubview(weiboLabel)
        v.addSubview(nameLabel)
        
        //设置布局
        weiboLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(v.snp_centerX)
            make.top.equalTo(v.snp_top)
            
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(v.snp_bottom)
            make.centerX.equalTo(v.snp_centerX)
        }
    }
}
